import { useWebSocket as _useWebSocket } from '@vueuse/core'
import { useStore } from '@/store'
import { message as Message } from 'ant-design-vue'
import { ref, watch } from 'vue'
import { isFunction } from '@/utils/is'

interface wsRef {
  value: wsInterface
}

interface wsInterface {
  close?: () => void
  [propName: string]: any
}

export function useWebSocket(mutationName = 'UPDATE_WS_DATA') {
  const store = useStore()
  const ws: wsRef = ref({})
  const colseVoluntary = ref(false)

  function initWs() {
    const token = store.getters['user/token']
    const activityId = store.getters['asyncRoute/curActive']?.id

    if (activityId) {
      ws.value = _useWebSocket(`${process.env.VUE_APP_API_WS}/${token}/${activityId}`, {
        onMessage: onWSMessage,
        onDisconnected: () => {
          if (!colseVoluntary.value) {

          }
          colseVoluntary.value = false
        },
        autoReconnect: {
          retries: 3,
          delay: 3000,
          onFailed() {
            Message.warn('网络连接不稳定，请检查网络设置并刷新页面')
          },
        },
        heartbeat: {
          message: `{"eventCode":"HeartBeat", "actid": ${activityId}}`,
          interval: 6000,
        },
      })
    }
  }

  initWs()
  function onWSMessage(ws, e) {

    const data = JSON.parse(e.data)

    if (data.eventCode !== 'HeartBeat') {
      store.commit(`websocket/${mutationName}`, data)
    }
  }

  watch(
    () => store.state.asyncRoute.curActive?.id,
    (val) => {
      console.log('活动改变，重新发起新的 WebSocket', val)
      colseVoluntary.value = true
      isFunction(ws.value?.close) && ws.value?.close!()
      initWs()
    },
  )

  return {
    ...ws.value,
    initWs,
  }
}
